package hall

import (
	"context"
	"github.com/tianjigames/fairy/constants"
	"github.com/tianjigames/fairy/manager"
	"github.com/tianjigames/fairy/model"
	protos2 "github.com/tianjigames/fairy/protos"
	"github.com/tianjigames/fairy/util"
	"github.com/topfreegames/pitaya"
	"github.com/topfreegames/pitaya/component"
	constants2 "github.com/topfreegames/pitaya/constants"
	"github.com/topfreegames/pitaya/logger"
)

type GameHandler struct {
	component.Base
}

func NewGameHandler() *GameHandler {
	return &GameHandler{}
}

func (p *GameHandler) BeginGame(ctx context.Context,req *protos2.CLBeginGame) (*protos2.CLBeginGame,error)  {
	s := pitaya.GetSessionFromCtx(ctx)
	accountId := s.Int64(constants.UIdKey)
	player := manager.LoginManager.GetLoginPlayer(s.UID())

	if player == nil || player.M_nLoginPlayerState != model.PlayerLoginNormal {
		logger.Log.Errorf("BeginGame failed,accountId=%d not login",accountId)
		return nil,constants2.ErrReturnNil
	}

	accountData := player.AccountData
	if accountData == nil {
		logger.Log.Errorf("BeginGame failed,accountId=%d,accountData=nil",accountId)
		return nil,constants2.ErrReturnNil
	}

	if accountData.ForbidLoginTime >= util.Now() {
		logger.Log.Errorf("BeginGame failed,accountId=%d,account forbid",accountId)
		return nil,constants2.ErrReturnNil
	}

	reply := &protos2.WLCheckLoginNumRet{}
	err := pitaya.RPC(ctx, constants.LWCheckLoginNumRoute,reply,&protos2.LWCheckLoginNum{PlayerId: req.PlayerId})
	if err != nil {
		logger.Log.Errorf("BeginGame failed,error:%s",err.Error())
		return nil,err
	}

	err = manager.LoginManager.CheckServerOnlineNum(ctx,reply)
	if err != nil {
		logger.Log.Errorf("BeginGame failed,error:%s",err.Error())
		return nil,err
	}

	return nil,constants2.ErrReturnNil
}

/**
游戏服上有玩家退出 提示当前等待登录游戏服的玩家进入游戏服
 */
func (p *GameHandler) PlayerLogout(req *protos2.WLPlayerLogout) (*protos2.WLPlayerLogout,error) {
	err := manager.LoginManager.WaitQueuePoll()
	if err != nil {
		logger.Log.Errorf("[GameHandler] PlayerLogout failed,error:%s",err.Error())
		return nil,err
	}

	return nil,constants2.ErrReturnNil
}







